package com.gzz.common;

import cn.hutool.core.util.StrUtil;
import com.gzz.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import static com.gzz.common.RedisUtils.User_Login_Key;
import static com.gzz.common.RedisUtils.User_Login_TTL;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

	private StringRedisTemplate stringRedisTemplate;

	public LoginInterceptor(StringRedisTemplate stringRedisTemplate){
		this.stringRedisTemplate=stringRedisTemplate;
	}
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String token = request.getHeader("token");
		// 判定token 是否为空
		if(StrUtil.isBlank(token)){
			//验证不通过，拦截
			response.setStatus(401);
			log.debug("11111");
			return false;
		}
		// 解析token,获取用户id
		Long id = JWTUtils.parseToken(token);
		String tokenKey = User_Login_Key+id.toString();
		String s = stringRedisTemplate.opsForValue().get(tokenKey);
        if (StrUtil.isBlank(s)||!s.equals(token)){
		   response.setStatus(401);
		   return false;
	    }
		Long expire = stringRedisTemplate.getExpire(tokenKey);
		//还剩30分钟过期刷新
		if(expire<=30*60){
			stringRedisTemplate.expire(tokenKey,User_Login_TTL, TimeUnit.MINUTES);
		}

		return true;
	}
}
